﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using IOA.MES.Client.Settings;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using IOA.MES.Client.Framing.PLCUtils;
using System.IO.Ports;
using System.Windows.Threading;
using Microsoft.Win32;
using System.Net.NetworkInformation;
using System.Configuration;

namespace IOA.MES.Client.Framing
{
    /// <summary>
    /// FramingIndex.xaml 的交互逻辑
    /// </summary>
    public partial class FramingIndex : Window
    {
        private WinFramingImage _winImages = null;
        //private string curDirectory;
        //private string folder = string.Empty;
        //private FileSystemWatcher dataFileWatcher;
        private int readImageDelay = 0;
        private McNetClient client;

        //是否加组件条码水印
        //public static bool IsPrintCode =  Convert.ToBoolean(ConfigurationManager.AppSettings["IsPrintCode"]);
        ////是否加机台水印                                     
        //public static bool IsPrintLine =  Convert.ToBoolean(ConfigurationManager.AppSettings["IsPrintLine"]);
        ////是否加日期水印                                     
        //public static bool IsPrintDate =  Convert.ToBoolean(ConfigurationManager.AppSettings["IsPrintDate"]);
        ////是否加时间水印                                     
        //public static bool IsPrintTime =  Convert.ToBoolean(ConfigurationManager.AppSettings["IsPrintTime"]);
        //是否加组件条码水印
        public static bool IsPrintCode = BaseEnv.GetStorage("IsPrintCode") != null ? Convert.ToBoolean(BaseEnv.GetStorage("IsPrintCode")) : false;
        //是否加机台水印
        public static bool IsPrintLine = BaseEnv.GetStorage("IsPrintLine") != null ? Convert.ToBoolean(BaseEnv.GetStorage("IsPrintLine")) : false;
        //是否加日期水印
        public static bool IsPrintDate = BaseEnv.GetStorage("IsPrintDate") != null ? Convert.ToBoolean(BaseEnv.GetStorage("IsPrintDate")) : false;
        //是否加时间水印
        public static bool IsPrintTime = BaseEnv.GetStorage("IsPrintTime") != null ? Convert.ToBoolean(BaseEnv.GetStorage("IsPrintTime")) : false;
        //设置图片保存路径
        public static string PhotoFile  = BaseEnv.GetStorage("FramePhotoFile") ?? BaseEnv.LocalDirectory;
        //public static string PhotoFile  = ConfigurationManager.AppSettings["FramePhotoFile"];
        public FramingIndex()
        {
            InitializeComponent();
            CheckUseRole();
        }
        private void CheckUseRole()
        {
            string macAddress = "";
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    macAddress = nic.GetPhysicalAddress().ToString();
                    break;
                }
            }
            RegistryKey aisun = Registry.CurrentUser.OpenSubKey("sun");
            if (aisun == null)
            {
                Application.Current.Shutdown();
            }
            else
            {
                //解密
                string desAddress = MD5Security.DESDecrypt(aisun.GetValue("id").ToString().Trim());
                if (macAddress != desAddress)
                {
                    Application.Current.Shutdown();
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitMachines();
            int.TryParse(BaseEnv.GetStorage("FrameReadImageDelay"), out readImageDelay);
            txtReadImageDelay.Text = readImageDelay.ToString();
            cbTakePhotos.IsChecked = true;
            cbCheckBoxCode.IsChecked = true;
            cbScanBoxCode.IsChecked = false;
            txtBoxCode.IsEnabled = false;
            var hwnd_source = (System.Windows.Interop.HwndSource)PresentationSource.FromVisual(this);
            var hwnd_target = hwnd_source.CompositionTarget;
            hwnd_target.RenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
            CreateAccessDb();
            TryConnectTCP();
            //扫码枪
            //TryComScan();
        }
        //创建Access数据库
        private void CreateAccessDb()
        {
            var dbString = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={PhotoFile}\\UnionImages.mdb";
            try
            {
                ADOX.Catalog catalog = new ADOX.Catalog();
                catalog.Create(dbString);
                ADOX.Table table = new ADOX.Table(); // 创建表
                table.Name = "image_info";  //表名字
                // 字段1
                ADOX.Column idColumn = new ADOX.Column();
                idColumn.ParentCatalog = catalog;
                idColumn.Name = "id";
                idColumn.Type = ADOX.DataTypeEnum.adInteger;
                idColumn.Properties["AutoIncrement"].Value = true;  // 设置该字段不是必需字段，插入数据的时候可以不考虑向该字段插入数据
                table.Columns.Append(idColumn, ADOX.DataTypeEnum.adInteger, 0);// 设置字段数据类型   DataTypeEnum.adVarWChar是文本类型

                ADOX.Column codeColumn = new ADOX.Column();
                codeColumn.ParentCatalog = catalog;
                codeColumn.Name = "code";
                codeColumn.Properties["AutoIncrement"].Value = false; // 设置该字段不是必需字段，插入数据的时候可以不考虑向该字段插入数据
                table.Columns.Append(codeColumn, ADOX.DataTypeEnum.adVarChar); // 设置字段数据类型   DataTypeEnum.adVarWChar是文本类型

                ADOX.Column machineNameColumn = new ADOX.Column();
                machineNameColumn.ParentCatalog = catalog;
                machineNameColumn.Name = "machine_name";
                machineNameColumn.Properties["AutoIncrement"].Value = false; // 设置该字段不是必需字段，插入数据的时候可以不考虑向该字段插入数据
                table.Columns.Append(machineNameColumn, ADOX.DataTypeEnum.adVarChar); // 设置字段数据类型   DataTypeEnum.adVarWChar是文本类型

                ADOX.Column fielNameColumn = new ADOX.Column();
                fielNameColumn.ParentCatalog = catalog;
                fielNameColumn.Name = "file_name";
                fielNameColumn.Properties["AutoIncrement"].Value = false; // 设置该字段不是必需字段，插入数据的时候可以不考虑向该字段插入数据
                table.Columns.Append(fielNameColumn, ADOX.DataTypeEnum.adVarChar);  // 设置字段数据类型   DataTypeEnum.adVarWChar是文本类型

                ADOX.Column timeColumn = new ADOX.Column();
                timeColumn.ParentCatalog = catalog;
                timeColumn.Name = "time";
                timeColumn.Properties["AutoIncrement"].Value = false; // 设置该字段不是必需字段，插入数据的时候可以不考虑向该字段插入数据
                table.Columns.Append(timeColumn, ADOX.DataTypeEnum.adVarChar);  // 设置字段数据类型   DataTypeEnum.adVarWChar是文本类型
                catalog.Tables.Append(table);
                CommonMessage.Log(LogLevel.Info, $"{dbString}创建成功");
            }
            catch (Exception e)
            {
                CommonMessage.Log(LogLevel.Info, $"{dbString} {e.Message}");
            }
        }
        public void TryComScan()
        {
            SerialPort serialPort = new SerialPort();
            serialPort.PortName = "COM5"; //指定串口号
            serialPort.BaudRate = 9600; //指定波特率
            //奇偶校验
            serialPort.Parity = Parity.None;
            //停止位
            serialPort.StopBits = StopBits.One;
            //数据位
            serialPort.DataBits = 8;
            //忽略null字节
            serialPort.DiscardNull = true;
            serialPort.RtsEnable = true;
            serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            serialPort.Open(); 
            CommonMessage.Log(LogLevel.Info, $"打开串口成功");
        }
        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            CommonMessage.Log(LogLevel.Info, $"监听扫码枪");
            string indata = sp.ReadExisting().Trim();
            CommonMessage.Log(LogLevel.Info, $"监听到的数据：{indata}");
            Dispatcher.Invoke(new Action(()=>
                this.txtBarCode.Text = indata
            ));
        }
       

        private void TryConnectTCP()
        {
            var ipAddress = BaseEnv.GetStorage("FrameIpAddress") ?? string.Empty;
            var port = BaseEnv.GetStorage("FramePort") ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(ipAddress) && !string.IsNullOrWhiteSpace(port))
            {
                client = new McNetClient(this, ipAddress, Convert.ToInt32(port), OnTcpStatusChange, 0, 5000);
                client.Connect();
            }
        }
        /// <summary>
        /// 扫描组件条码
        /// </summary>
        public void txtBarCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            int ret = client.Read();
            if (ret != 1)
            {
                CommonMessage.Alert(this, $"从流水线D400中读到的数据是{ret}，组件未到位，无法执行拍照程序,请按放行按钮");
                PlayFailAudioTack($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                this.txtBarCode.Text = String.Empty;
                this.txtBarCode.Focus();
                return;
            }
            TodoPhotoTake();//手动扫码
        }
        
       
        /// <summary>
        /// 手动扫码枪专用
        /// </summary>
        public void TodoPhotoTake()
        {
            string machineName = "L4-接线盒拍照";
            bool check = cbCheckBoxCode.IsChecked.Value;
            bool tack = cbTakePhotos.IsChecked.Value;
            string barCodeText = txtBarCode.Text.Trim();
            if (string.IsNullOrWhiteSpace(barCodeText))
            {
                CommonMessage.Alert(this, $"请扫入组件条码\r\n Please scan component code：\r\n{barCodeText}");
                PlayFailAudioTack($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                //client.Send(-1);//改成-1
                return;
            }
            if (check == true)
            {
                CommonMessage.Log(LogLevel.Info, $"开始验证条码{barCodeText}！！！");
                string sql = string.Format("select count(*) FROM {0} WHERE {1} = '{2}'",
                        DBHelper.TableName, DBHelper.ColumnName, barCodeText);
                if (Convert.ToInt32(DBHelper.ExecuteScalar(sql)) == 0)
                {
                    CommonMessage.Alert(this, $"组件不存在,请重新扫码\r\nComponent does not exist：\r\n{barCodeText}");
                    PlayFailAudioTack($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                    //client.Send(-1);//改成-1
                    this.txtBarCode.Text = String.Empty;
                    this.txtBarCode.Focus();
                    return;
                }
            }
            if (tack == true)
            {
                Thread.Sleep(1500);
                string imageName = string.Empty;
                var bytes = _winImages.GetUnionImages(barCodeText, machineName,out imageName);
                if (bytes.Length == 0 || !File.Exists(imageName))
                {
                    CommonMessage.Alert(this, $"组件{barCodeText}拍照失败，请重新扫码拍照！！");
                    PlayFailAudioTack($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                    CommonMessage.Log(LogLevel.Fatal, $"组件{barCodeText}拍照失败,图片 {imageName} 不存在");
                    this.txtBarCode.Text = String.Empty;
                    this.txtBarCode.Focus();
                    return;
                }
                var records = new Records
                {
                    Code = barCodeText,
                    MachineName = machineName,
                    OperateTime = DateTime.Now.ToString("F")
                };
                List<Records> _records = new List<Records>();
                _records.Add(records);
                var bmi = new BitmapImage();
                bmi.BeginInit();
                bmi.StreamSource = new MemoryStream(bytes);
                bmi.EndInit();
                imgPhoto.Source = null;
                imgPhoto.Source = bmi;
                gridRecords.ItemsSource = null;
                gridRecords.ItemsSource = _records;
                lbTotal.Content = Convert.ToInt32(this.lbTotal.Content) + 1;
                txtBarCode.Text = String.Empty;
                if (txtLineStatus.Text.Equals("已连接"))
                {
                    //写入数据库 条码 操作机台 过站时间 图片位置
                    string sql = String.Format($"insert into [image_info] ([code],[machine_name],[file_name],[time]) values('{barCodeText}','{machineName}','{imageName}','{records.OperateTime}')");
                    var dbString = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={PhotoFile}\\UnionImages.mdb";
                    int count = DBHelper.OlExecuteNonQuery(dbString, sql);
                    if (count > 0)
                    {
                        CommonMessage.Log(LogLevel.Info, $"条码{barCodeText}保存成功！");
                        client.Send(1);//发送1
                        PlayFailAudioTack($"{BaseEnv.LocalDirectory}\\res\\audio\\Success.wav");
                    }
                    else
                    {
                        CommonMessage.Log(LogLevel.Info, $"条码{barCodeText}保存失败！");
                        CommonMessage.Alert(this, $"组件{barCodeText}拍照失败，请重新扫码拍照！！");
                        PlayFailAudioTack($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                    }
                }
                else
                {
                    CommonMessage.Alert(this, $"与流水线的PLC连接断开，取消发送数据，请检查网络：");
                    PlayFailAudioTack($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                }
            }
        }
        /// <summary>
        /// 自动扫码枪专用
        /// </summary>
        public void TodoAutoPhoto()
        {
            bool check = false;
            bool tack = false;
            string machineName = "L4-接线盒拍照";
            string barCodeText = string.Empty;
            Dispatcher.Invoke(new Action(() =>
            {
                check = cbCheckBoxCode.IsChecked.Value;
                tack = cbTakePhotos.IsChecked.Value;
                barCodeText = txtBarCode.Text;
            }));
            if (string.IsNullOrWhiteSpace(barCodeText))
            {
                CommonMessage.Alert(this, $"请扫入组件条码\r\n Please scan component code：\r\n{barCodeText}");
                PlayAutoAudio($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                client.Send(-1);
                return;
            }
            if (check == true)
            {
                CommonMessage.Log(LogLevel.Info, $"开始验证！！！");
                string sql = string.Format("select count(*) FROM {0} WHERE {1} = '{2}'",
                        DBHelper.TableName, DBHelper.ColumnName, barCodeText);
                if (Convert.ToInt32(DBHelper.ExecuteScalar(sql)) == 0)
                {
                    CommonMessage.Alert(this, $"组件不存在\r\nComponent does not exist：\r\n{barCodeText}");
                    PlayAutoAudio($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                    client.Send(-1);
                    return;
                }
            }
            if (tack == true)
            {
                Thread.Sleep(1500);
                string imageName = string.Empty;
                var bytes = _winImages.GetUnionImages(barCodeText, machineName, out imageName);
                var records = new Records
                {
                    Code = barCodeText,
                    MachineName = machineName,
                    OperateTime = DateTime.Now.ToString("F")
                }; 
                List<Records> _records = new List<Records>();
                _records.Add(records);
                Dispatcher.Invoke(new Action(()=>
                {
                    var bmi = new BitmapImage();
                    bmi.BeginInit();
                    bmi.StreamSource = new MemoryStream(bytes);
                    bmi.EndInit();
                    imgPhoto.Source = bmi;
                    bmi = null;
                    gridRecords.ItemsSource = null;
                    gridRecords.ItemsSource = _records;
                    mediaElResult.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Success.wav");
                    mediaElResult.Play();
                    lbTotal.Content = Convert.ToInt32(lbTotal.Content) + 1;
                    txtBarCode.Text = "";
                    txtBarCode.Focus();
                    if (txtLineStatus.Text.Equals("已连接"))
                    {
                        client.Send(1);
                    }
                })
                );
            }

        }
        private void PlayAutoAudio(string uri)
        {
            Dispatcher.Invoke(new Action(()=>
            { 
                mediaElResult.Source = new Uri(uri);
                mediaElResult.Play();
                txtBarCode.Focus();
             })
            );
        }
        private void PlayFailAudioTack(string uri)
        {
            mediaElResult.Source = new Uri(uri);
            mediaElResult.Play();
            txtBarCode.Focus();
        }
        public void OnTcpStatusChange(bool connected)
        {
            if (connected)
            {
                txtLineStatus.Text = "已连接";
                txtLineStatus.Foreground = new SolidColorBrush(Colors.Green);
            }
            else
            {
                txtLineStatus.Text = "已断开";
                txtLineStatus.Foreground = new SolidColorBrush(Colors.Red);
            }
        }
        public void OnChangeTextKey(bool connected)
        {
            if (connected)
            {
                this.txtBarCode.KeyDown += this.txtBarCode_KeyUp; ;
            }
            else
            {
                txtLineStatus.Text = "已断开";
                txtLineStatus.Foreground = new SolidColorBrush(Colors.Red);
            }
        }

        

        public void OnDataReceived(List<byte> data)
        {

        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if (_winImages != null && PresentationSource.FromVisual(_winImages) != null)
            {
                _winImages.Close();
            }
            //var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //var settings = configFile.AppSettings.Settings;
            //settings["CbCheckBoxCode"].Value = this.cbCheckBoxCode.IsChecked.ToString();
            //configFile.Save(ConfigurationSaveMode.Modified);
            //ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            Environment.Exit(0);
        }

        private void cbTakePhotos_Checked(object sender, RoutedEventArgs e)
        {
            //if (cbTakePhotos.IsChecked == true && cbScanImages.IsChecked != true)
            if (cbTakePhotos.IsChecked == true)
            {
                this.WindowState = WindowState.Normal;
                this.Width = SystemParameters.WorkArea.Width / 3.0 * 2;
                this.Height = SystemParameters.WorkArea.Height;
                this.Left = 0;
                this.Top = 0;

                _winImages = new WinFramingImage();
                _winImages.Closed += _winImages_Closed;
                _winImages.Show();

                if (cbScanBoxCode.IsChecked == true)
                {
                    txtBoxCode.Focus();
                }
                else
                {
                    txtBarCode.Focus();
                }
            }
            else if (_winImages != null && PresentationSource.FromVisual(_winImages) != null)
            {
                this.WindowState = WindowState.Maximized;
                _winImages.Close();
            }
        }

        private void _winImages_Closed(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Maximized;
            cbTakePhotos.IsChecked = false;
        }

        private void cbScanBoxCode_Checked(object sender, RoutedEventArgs e)
        {
            if (cbScanBoxCode.IsChecked == true)
            {
                txtBoxCode.IsEnabled = true;
            }
            else
            {
                txtBoxCode.IsEnabled = false;
            }
        }
        

        #region 初始化数据

        public void InitMachines()
        {
            //var machines =   BaseEnv.InvokeApi<QueryMachinesResponse>("/api/Machine/QueryMachines", new { WorkshopCode = BaseEnv.WorkshopCode, MachineType = (int)MachineType.Framing }).Data.Machines;
            var machines = new List<Machine> { 
                new Machine() { MachineId = 1, MachineName ="L4-接线盒拍照"}
            };
            cbMachines.ItemsSource = machines;
            cbMachines.DisplayMemberPath = "MachineName";
            cbMachines.SelectedValuePath = "MachineId";
            if (machines.Any())
            {
                cbMachines.SelectedIndex = 0;
            }
        }

        

        #endregion

        /// <summary>
        /// 班次、机台选择
        /// </summary>
        private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //InitRecords();
            
        }

        /// <summary>
        /// 设置拍照延迟
        /// </summary>
        private void btnReadImageDelay_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtReadImageDelay.Text))
            {
                txtReadImageDelay.Text = "0";
            }
            try
            {
                var delay = Convert.ToInt32(txtReadImageDelay.Text.Trim());
                readImageDelay = delay;
                BaseEnv.SetStorage("FrameReadImageDelay", delay.ToString());
            }
            catch (Exception ex)
            {
                CommonMessage.Alert(this, "请输入数字");
            }
        }

        /// <summary>
        /// 启用/禁用监控
        /// </summary>
        private void cbScanImages_Checked(object sender, RoutedEventArgs e)
        {
            //txtBarCode.Text = "";
            //if (cbScanImages.IsChecked == true)
            //{
            //    BaseEnv.SetStorage("FrameScanImagesChecked", "1");
            //    txtBarCode.IsEnabled = false;
            //    if (!string.IsNullOrWhiteSpace(txtImageFolder.Text))
            //    {
            //        WatchDataChanges(txtImageFolder.Text);
            //    }

            //    this.WindowState = WindowState.Maximized;
            //    if (_winImages != null && PresentationSource.FromVisual(_winImages) != null)
            //    {
            //        _winImages.Close();
            //    }
            //}
            //else
            //{
            //    BaseEnv.SetStorage("FrameScanImagesChecked", "0");
            //    txtBarCode.IsEnabled = true;
            //    txtBarCode.Focus();
            //    WatchDataChanges(txtImageFolder.Text, false);

            //    if (cbTakePhotos.IsChecked == true)
            //    {
            //        this.WindowState = WindowState.Normal;
            //        this.Width = SystemParameters.WorkArea.Width / 3.0 * 2;
            //        this.Height = SystemParameters.WorkArea.Height;
            //        this.Left = 0;
            //        this.Top = 0;

            //        _winImages = new WinFramingImage();
            //        _winImages.Closed += _winImages_Closed;
            //        _winImages.Show();
            //    }
            //}
        }

        /// <summary>
        /// 选择监控路径
        /// </summary>
        private void btnSelectImageFile_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && Directory.Exists(dialog.SelectedPath))
            {
                //txtImageFolder.Text = dialog.SelectedPath;
                BaseEnv.SetStorage("FrameScanImagesFolder", dialog.SelectedPath);
                //if (cbScanImages.IsChecked == true)
                //{
                //    WatchDataChanges(dialog.SelectedPath);
                //}
            }
            
        }
        

        /// <summary>
        /// 开始监听图片文件
        /// </summary>
        private void WatchDataChanges(string folder, bool monitor = true)
        {
            //if (monitor)
            //{
            //    CommonMessage.Log(LogLevel.Debug, $"开始监听文件夹：{folder}");

            //    dataFileWatcher = new FileSystemWatcher(folder);
            //    dataFileWatcher.IncludeSubdirectories = true;
            //    dataFileWatcher.Created += DataFileWatcher_Changed;
            //    dataFileWatcher.EnableRaisingEvents = true;
            //    dataFileWatcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess
            //                           | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;
            //}
            //else
            //{
            //    CommonMessage.Log(LogLevel.Debug, $"取消监听文件夹：{folder}");
            //    if (dataFileWatcher != null)
            //    {
            //        dataFileWatcher.EnableRaisingEvents = false;
            //    }
            //}
        }

        /// <summary>
        /// 文件变化监控
        /// </summary>
        private void DataFileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            CommonMessage.Log(LogLevel.Debug, $"发现文件【{e.ChangeType}】：{e.FullPath}");

            if (!new[] { ".jpg", ".jpeg", ".png", ".bmp" }.Contains(Path.GetExtension(e.FullPath), StringComparer.CurrentCultureIgnoreCase))
            {
                CommonMessage.Log(LogLevel.Debug, $"跳过文件：{e.FullPath}");
                return;
            }
            Thread.Sleep(readImageDelay * 1000);

            Dispatcher.Invoke(new Action(() =>
            {

                string[] stingArry = System.IO.Path.GetFileNameWithoutExtension(e.FullPath).Split('_');
                txtBarCode.Text = stingArry[1];
                //线盒拍照处命名：日期_条码_文件夹路径1层_文件夹路径2层....处理为取第一个下划线的后的值
                if (stingArry[stingArry.Length - 1].ToUpper() == "FMG")
                {
                    //ViaSite(File.ReadAllBytes(e.FullPath));
                }
            }));
        }

        
        /// <summary>
        /// 扫接线盒
        /// </summary>
        private void txtBoxCode_KeyUp(object sender, KeyEventArgs e)
        {
            txtBarCode.Focus();
        }


        private void Menu_Click(object sender, RoutedEventArgs e)
        {
            switch (((MenuItem)sender).Name)
            {
                //case "btnSettings":
                //    new SettingsIndex().ShowDialog();
                //    break;
                case "btnImageSettings":
                    new ImageSettingsIndex().ShowDialog();
                    break;
                case "btnMissingRecords":
                    new MissingSiteRecord(Convert.ToInt32(cbMachines.SelectedValue)).Show();
                    break;
                case "btnLineSetting":
                    new WinFrameSetting().ShowDialog();
                    TryConnectTCP();
                    break;
                case "btnLogout":
                    //new LoginWindow(false).Show();
                    //this.Hide();
                    break;
                case "btnAbout":
                    MessageBox.Show($"AISUNMes Product Version:{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion}");
                    break;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_winImages != null && PresentationSource.FromVisual(_winImages) != null)
            {
                _winImages.Close();
            }
        }
    }
}
